package com.roc.web.action.windcontroll;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.bean.ChangeCheckCountBean;
import com.roc.bean.ErrorCountBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.RiskSurveyOrder;
import com.roc.service.IExcelService;
import com.roc.service.RegisterOrderProcessService;
import com.roc.util.Constance;
import com.roc.util.OrderType;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
/**
 * 差错处理
 * @author 160711BB
 *
 */
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/orpro")
public class OrderProcessAction extends PaginationBaseAction{
	
	private Logger logger = LogManager.getLogger(OrderProcessAction.class);
	
	private OrderProcessSearchCondition searchCondition;
	
	private RiskSurveyOrder rso;
	
	private String riskId;
	
	private String delId;
	
	private File upload;
	
	private String importNum;
	
	private InputStream excelFile;
	
	@Autowired
	private IPageService pagenitionService;
	
	@Autowired
	private RegisterOrderProcessService registerOrderProcessService;
	
	@Autowired
	private IExcelService excelService;
	
	private OrderType orderType;
	/**
	 * 查询页面初始化
	 * @return
	 */
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/windControllSta/queryOrderProcessJsp.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String queryOrderProcessJsp(){
		//LinkedHashMap<String, String> orderTypeMap  =OrderType.getAllEnumLinkedHashMap();
		try {
			Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
				addActionError("当前登录账号无权限访问!!!");
				return ERROR;
			}
			org();
		
			//getRequest().setAttribute("orderTypeMap",orderTypeMap);
		} catch (Exception e) {
			logger.error("差错管理登记页面初始化异常："+e);
		}
		return SUCCESS;
	}
	
	/**
	 * 查询
	 * @return
	 */
	@Action(value = "queryOrderProcessList", results = { @Result(name = "success", location = "/pages/windControllSta/queryOrderProcessJsp.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String queryOrderProcessList(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		try {
			if(searchCondition==null){
				searchCondition=(OrderProcessSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new OrderProcessSearchCondition();
				}
			}
			int rows=pagenitionService.count(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAll(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);				
			}
			
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
		
			setSearchToConditionSession(searchCondition);
			org();
		} catch (Exception e) {
			logger.error("查询调单管理数据异常："+e.getMessage());
			addActionError(e.getMessage());
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	/**
	 * 登记页面初始化
	 * @return
	 */
	@Action(value = "registerInit", results = { @Result(name = "success", location = "/pages/windControllSta/registerJsp.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String registerInit(){
		
		try {
			org();
		} catch (Exception e) {
			logger.error("登记页面初始化异常："+e);
			
		}
		
		return SUCCESS;
	}
	
	/**
	 * 登记
	 * @return
	 */
	@Action(value = "registerOrderProcess", results = { @Result(name = "success", location = "/pages/windControllSta/queryOrderProcessJsp.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String registerOrderProcess(){
		Operators logingMerchant = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		Map<String,Object> resMap = new HashMap<String, Object>();
		try {
			resMap = registerOrderProcessService.registerOrderPro(rso, logingMerchant);
			org();
			addActionError((String) resMap.get("msg"));
		} catch (Exception e) {
			logger.error("登记失败："+e);
			addActionError("差错管理登记异常");
		}
		return SUCCESS;
	}
	
	/**
	 * 修改页面初始化
	 * @return
	 */
	@Action(value = "modifyInit", results = { @Result(name = "success", location = "/pages/windControllSta/modifyInitJsp.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String modifyInit(){
		try {
			rso = registerOrderProcessService.obtainRiskOrderDetail(riskId);
			org();
		} catch (Exception e) {
			logger.error("修改页面初始化异常："+e);
		}
		
		return SUCCESS;
	}
	
	/**
	 * 修改
	 * @return
	 */
	@Action(value = "modifyRiskOrder", results = { @Result(name = "success", location = "/pages/windControllSta/queryOrderProcessJsp.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String modifyRiskOrder(){
		Operators logingMerchant = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		Map<String,Object> resMap = new HashMap<String, Object>();
		try {
			resMap = registerOrderProcessService.modifyRiskOrder(rso, logingMerchant);
			org();
			addActionError((String) resMap.get("msg"));
		} catch (Exception e) {
			logger.error("修改差错管理数据异常："+e);
			addActionError("差错管理修改异常");
		}
		
		return SUCCESS;
	}
	
	/**
	 * 删除
	 * @return
	 */
	@Action(value = "deleteRiskOrder", results = { @Result(name = "success", location = "/pages/windControllSta/queryOrderProcessJsp.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String deleteRiskOrder(){
		Operators logingMerchant = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		Map<String,Object> resMap = new HashMap<String, Object>();
		try {
			resMap = registerOrderProcessService.deleteRiskOrder(delId, logingMerchant);
			org();
			addActionError((String) resMap.get("msg"));
		} catch (Exception e) {
			logger.error("删除差错管理数据异常："+e);
			addActionError("删除差错管理异常");
		}
		return SUCCESS;
	}
	
	/**
	 * 批量导入页面初始化
	 * @return
	 */
	@Action(value = "batchImportInit", results = { @Result(name = "success", location = "/pages/windControllSta/batchImportJsp.jsp"),
			@Result(name = "error", location = "/error.jsp")})
	public String batchImportInit(){
		try {
			
		} catch (Exception e) {
			
		}
		
		return SUCCESS;
	}
	
	/**
	 * 批量导入
	 * @return
	 */
	@Action(value = "exportErrorCountList", interceptorRefs = {
			@InterceptorRef(value = "token"),
			@InterceptorRef(value = "rocDefaultStack", params = {
					"fileUpload.allowedExtensions", "xlsx",
					"fileUpload.maximumSize", "100000000" }) }, results = {
			@Result(location = "/pages/windControllSta/batchImportJsp.jsp"),
			@Result(name = "error", location = "/error.jsp"),
			@Result(name = "invalid.token", location = "/error.jsp")})
	public String merInfoBatchImport(){
		Operators oper = (Operators) ActionContext.getContext().getSession().get(
				Constant.SESSION_LOGIN_MERCHANT);
		try {
			Map<String ,Object> resultMap = registerOrderProcessService.batchImportOrder(upload, oper,importNum);

			addActionError(resultMap.get("msg").toString());
			
		} catch (Exception e) {
			logger.error("差错批量导入异常："+e.getMessage());
			addActionError("差错批量导入异常："+e.getMessage());
			return ERROR;
		}
		
		return SUCCESS;
	}
	
	/**
	 * 导出
	 * @return
	 */
	@Action(value="exportOrderProcessList",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xls",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/windControllSta/queryOrderProcessJsp.jsp") })
	public String exportOrderProcessList(){
		try {
			if(searchCondition==null){
				searchCondition=(OrderProcessSearchCondition)getSearchConditionFromSession();
				if(searchCondition==null){
					searchCondition=new OrderProcessSearchCondition();
				}
			}
			int row = registerOrderProcessService.queryOrderCount(searchCondition);
			
			List<ErrorCountBean> errList = new ArrayList<ErrorCountBean>();
			if(row>0){
				
				errList = registerOrderProcessService.queryOrderList(searchCondition, calcuStart(getCurrentPage()), row);
			
			}
			
			SXSSFWorkbook  work=excelService.exportErrorCountList(errList, searchCondition);

			 ByteArrayOutputStream output = new ByteArrayOutputStream();  
			         work.write(output);  
			   
			        byte[] ba = output.toByteArray();  
			         excelFile = new ByteArrayInputStream(ba);  
			         output.flush();  
			         output.close(); 
		} catch (Exception e) {
			logger.error("差错列表导出异常："+e);
			addActionError("差错列表导出异常："+e.getMessage());
		}
		
		return SUCCESS;
	}
	
	public void org(){
		
		getRequest().setAttribute("reasonCdMap",ConfigProperties.dealReasonCdMap());
		getRequest().setAttribute("orderTypeMap",OrderType.getAllEnumLinkedHashMap());

	}
	

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_ORDER_PROCESS_QUERY, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (OrderProcessSearchCondition)getSession().getAttribute(SEARCH_SESSION_ORDER_PROCESS_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE+"";
	}

	public RiskSurveyOrder getRso() {
		return rso;
	}

	public void setRso(RiskSurveyOrder rso) {
		this.rso = rso;
	}

	public OrderProcessSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(OrderProcessSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public String getRiskId() {
		return riskId;
	}

	public void setRiskId(String riskId) {
		this.riskId = riskId;
	}

	public String getDelId() {
		return delId;
	}

	public void setDelId(String delId) {
		this.delId = delId;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}
	
	public String getExcelName() {
		String excelName="差错列表"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getImportNum() {
		return importNum;
	}

	public void setImportNum(String importNum) {
		this.importNum = importNum;
	}
	
	
	
}
